package db

import (
	"context"
	"fmt"
	"github.com/name5566/leaf/log"
	"github.com/qiniu/qmgo"
	"math/rand"
)

type MongoMiddleware struct {
	client   *qmgo.Database
	database string // 默认数据库名
	Client   *qmgo.Database
}

var Db *MongoMiddleware

func init() {
	//mongodb://username:password@host:port
	client, err := NewMongoMiddleware("mongodb://root:example@39.99.157.152:27017/", 100, "AccDB")
	//client, err := NewMongoMiddleware("mongodb://root:OG2KUwwIBAr25gwc@127.0.0.1:27017/", 100, "AccDB")
	if err != nil {
		log.Fatal("db start is error msg is " + err.Error())
	}
	Db = client
}

// NewMongoMiddleware 创建 MongoDB 中间件
func NewMongoMiddleware(uri string, poolLimit int, database string) (*MongoMiddleware, error) {
	ctx := context.Background()
	Newclient, err := qmgo.NewClient(ctx, &qmgo.Config{Uri: uri})
	if err != nil {
		return nil, fmt.Errorf("连接 MongoDB 失败: %v", err)
	}

	return &MongoMiddleware{client: Newclient.Database(database), database: database, Client: Newclient.Database(database)}, nil
}

// Close 关闭 MongoDB 客户端
func (m *MongoMiddleware) Close() {

}

// Insert 插入数据
func (m *MongoMiddleware) Insert(tableName string, data interface{}) error {
	_, err := m.client.Collection(tableName).InsertOne(context.Background(), data)
	if err != nil {
		return fmt.Errorf("插入数据失败: %v", err)
	}
	return nil
}
func (m *MongoMiddleware) FindOne(tableName string, query, result interface{}) error {
	err := m.client.Collection(tableName).Find(context.Background(), query).One(result)
	if err != nil {
		return fmt.Errorf("查询单条数据失败: %v", err)
	}
	return nil
}

// Find 查询数据
func (m *MongoMiddleware) Find(tableName string, query, result interface{}) error {
	err := m.client.Collection(tableName).Find(context.Background(), query).All(result)
	if err != nil {
		return fmt.Errorf("查询数据失败: %v", err)
	}
	return nil
}

// Find 查询数据
func (m *MongoMiddleware) FindSort(tableName string, query, result interface{}, sortOrder int, sortField string) error {
	err := m.client.Collection(tableName).Find(context.Background(), query).Sort(fmt.Sprintf("%d%s", sortOrder, sortField)).All(result)
	if err != nil {
		return fmt.Errorf("查询数据失败: %v", err)
	}
	return nil
}

// Update 更新数据
func (m *MongoMiddleware) Update(tableName string, selector, update interface{}) error {

	err := m.client.Collection(tableName).UpdateOne(context.Background(), selector, &update)
	if err != nil {
		return fmt.Errorf("更新数据失败: %v", err)
	}
	return nil
}

// Delete 删除数据
func (m *MongoMiddleware) Delete(tableName string, selector interface{}) error {
	err := m.client.Collection(tableName).Remove(context.Background(), selector)
	if err != nil {
		return fmt.Errorf("删除数据失败: %v", err)
	}
	return nil
}

// Find 从指定集合中查找文档

// Aggregate 执行聚合操作
func (m *MongoMiddleware) Aggregate(tableName string, pipeline interface{}, result interface{}) error {
	err := m.client.Collection(tableName).Aggregate(context.Background(), pipeline).All(result)
	if err != nil {
		return err
	}
	return nil
}
func (m *MongoMiddleware) AggregateOne(tableName string, pipeline interface{}, result interface{}) error {
	err := m.client.Collection(tableName).Aggregate(context.Background(), pipeline).One(result)
	if err != nil {
		return err
	}
	return nil
}
func (m *MongoMiddleware) RandNum(tableName string, selector interface{}, result interface{}) error {
	count, err := m.client.Collection(tableName).Find(context.Background(), selector).Count()
	if err != nil {
		log.Error("统计文档数量失败: %v\n", err)
		return fmt.Errorf("统计文档数量失败: %v\n", err)
	}
	if count == 0 {
		log.Error("未找到 user_id 为 1 的文档")
		return fmt.Errorf("未找到 user_id 为 1 的文档")
	}
	offset := rand.Intn(int(count))
	m.client.Collection(tableName).Find(context.Background(), selector).Skip(int64(offset)).Limit(1).One(result)
	if err != nil {
		log.Error("查询文档失败: %v\n", err)
		return fmt.Errorf("查询文档失败: %v\n", err)
	}
	return nil
}
